package com.ruizhong.centercontroll.util;
 

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;


@Data

public class CosUtil {
 

	private String secretId = "AKIDIUVN5bv53paDk9OTM6g470gBVdZI9xb3";
 

	private String secretKey = "KSN6cBct20pUxEvVyIQL3088N4bx7gLs";
 

	private String region = "ap-guangzhou";
 

	private String bucketName = "center-control-1320487003";
 

	private String path = "https://center-control-1320487003.cos.ap-guangzhou.myqcloud.com";
 
	public COSClient initCOSClient(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
		Region region = new Region(this.region);
		ClientConfig clientConfig = new ClientConfig(region);
		// 生成 cos 客户端。
		COSClient cosClient = new COSClient(cred, clientConfig);
		return cosClient;
	}
 
	/**
	 * 上传文件
	 */

	public String upLoad(MultipartFile file){
		try {
		    String filePath = file.getName();
			// 指定要上传的文件
//			File localFile = new File("G:\\svn\\图片\\背景图\\4k游戏壁纸_彼岸图网.jpg");
			// 指定要上传到 COS 上对象键
            String key = getFileKey(filePath);
            System.out.println(key + "key----------------------");
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(),null);

			COSClient cosClient1 = initCOSClient();
			PutObjectResult putObjectResult = cosClient1.putObject(putObjectRequest);
            // 设置权限(公开读)
            cosClient1.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            System.out.println("url------------" + path + "/"+ key);
			return path + "/"+ key;
		} catch (CosServiceException serverException) {
			serverException.printStackTrace();
		} catch (CosClientException clientException) {
			clientException.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
 
 
	/**
	 * 生成文件路径
	 *
	 * @return
	 */
	private String getFileKey(String originalfileName) {
		String filePath = "test/";
		//1.获取后缀名 2.去除文件后缀 替换所有特殊字符
		String fileType = originalfileName.substring(originalfileName.lastIndexOf("."));
		String fileStr = StrUtil.removeSuffix(originalfileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
		filePath +=  new DateTime().toString("yyyyMMddHHmmss") + "_" + fileStr + fileType;
		return filePath;
	}
 
}